package cn.nb12.xbox.utils;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nb12.xbox.po.Area;
import cn.nb12.xbox.po.Games;
import cn.nb12.xbox.po.Price;
import cn.nb12.xbox.service.PriceService;

public class GameUpdate extends Thread{
	
	private Logger log=LoggerFactory.getLogger(GameUpdate.class);
	private GenerateBusinessCodeService generateBusinessCodeService;
	private List<Games> games;
	private Area area;
	public GameUpdate(List<Games> games,Area area,GenerateBusinessCodeService generateBusinessCodeService) {
		this.area=area;
		this.games=games;
		this.generateBusinessCodeService=generateBusinessCodeService;
	}
	@Override
	public void run() {
		PriceService priceService=(PriceService)SpringContextUtil.getBean(PriceService.class);
		for (Games game : games) {
			log.info("更新"+game.getName()+":"+area.getCode()+"价格");
			//获得一个游戏链接
			String gameUrl = GetGame.getGameUrls(game.getCode(), area.getCode());
			Map<String, Object> info = GetInfo.getInfo(gameUrl);
			if(info!=null && info.size()==4) {
				String imgurl=(String)info.get("imgurl");
				String name=(String)info.get("name");
				String money=(String)info.get("money");
				String key=(String)info.get("key");
				Price price=new Price(generateBusinessCodeService.doWork(), NumUtil.getDouble(money, 0.0), game.getId(), area.getId(),key,"",name);
				Assist assist=new Assist();
				assist.setRequires(Assist.andEq("GAM_ID", game.getId()));
				assist.setRequires(Assist.andEq("ARE_ID", area.getId()));
				priceService.deletePrice(assist);
				priceService.insertNonEmptyPrice(price);
				
				//更新游戏名和图片链接
				if((game.getImgurl()==null || game.getImgurl().trim().length()<1) && (imgurl!=null && imgurl.length()>0)) {
					game.setImgurl((String)info.get("imgurl"));
				}
				if(((game.getName()==null || game.getName().trim().length()<1) && (name!=null && name.length()>0)) || (name!=null && !"".equals(name) && ("CNY".equals(area.getCurrency()) || "HKD".equals(area.getCurrency()) || "TWD".equals(area.getCurrency())))) {
					game.setName((String)info.get("name"));
				}
				
			}
			else {
				log.info("查到游戏没有数据，链接："+gameUrl);
			}
			log.info("当前线程："+GameUpdate.activeCount()+":"+Thread.activeCount());
		}
	}
}